package controllers

import (
	"errors"
	"math/rand"
	"os"
	"path"
	"strconv"
	"strings"
	"time"
)

type UploadController struct {
	BaseController
}

type uploadFiles struct {
	FileName string `json:"file_name"`
	FilePath string `json:"file_path"`
	Size     int64  `json:"size"`
	Ext      string `json:"ext"`
}

// @Title upload image
// @Description 上传图片
// @router /image [post]
func (c *UploadController) Image() {
	f, header, err := c.GetFile("image")
	if err != nil {
		c.Error(err)
		return
	}
	defer f.Close()

	p := "static/uploads/" + time.Now().Format("20060102")
	if _, err = os.Stat(p); err != nil {
		err := os.MkdirAll(p, 777)
		if err != nil {
			c.Error(err)
			return
		}
	}

	ext := path.Ext(header.Filename)
	filename := strconv.Itoa(int(time.Now().Unix())) + strconv.Itoa(int(rand.Int63n(9999))) + ext
	fp := p + "/" + filename

	exts := strings.ToLower(".jpe, .jpge, .gif, .png")
	if b := strings.Contains(exts, strings.ToLower(ext)); !b {
		c.Error(errors.New("只允许上传后缀为:" + exts + "的文件"))
		return
	}

	allowSize := int64(20480000)
	if header.Size > allowSize {
		c.Error(errors.New("上传文件太大了"))
		return
	}

	if err := c.SaveToFile("image", fp); err != nil {
		c.Error(err)
		return
	}

	file := uploadFiles{
		FileName: filename,
		FilePath: strings.Replace(fp, "static/uploads/", "http://image.rcenet.com/", 1),
		Size:     header.Size,
		Ext:      ext,
	}

	c.Success(file)
}
